<template>
  <div class="app-container" v-loading="pageLoading">
    <el-row :gutter="10">
      <el-col :span="8">
        <div class="panel-info">
          <div class="panel-title">设备类型树</div>
          <div class="panel-body">
            <el-button v-if="treeData.length <= 0" v-permission='"adminDept.add"' @click="createNode(null)">创建
            </el-button>
            <el-tree ref="tree" :data="treeData" node-key="id" :props="{ children: 'child' }"
              :default-expand-all="false" :expand-on-click-node="false" :allow-drop="allowDrop"
              :defaultExpandedKeys="defaultExpandedKeys" :filter-node-method="filterMethod" @node-drop="afterDrop"
              @node-expand="nodeExpand" @node-click="nodeClick" @node-collapse="nodeCollapse">
              <div class="custom-tree-node" slot-scope="{ data }">
                <div style="flex: 1; overflow: hidden">
                  <i v-if="data.child && data.child.length > 0" class="fa el-icon-s-tools text-blue t-14"></i>
                  <i v-else class="fa el-icon-setting text-blue t-14"></i>
                  <span class="text-bold ml-10">[{{ data.machine_type_code }}] {{ data.machine_type_name }}</span>
                </div>
                <div>
                  <i class="fa fa-pencil-square-o text-blue pl-10" v-permission='"adminDept.edit"' aria-hidden="true"
                    title="编辑" @click.prevent.stop="editNode(data)"></i>
                  <i class="fa fa-toggle-right text-green pl-10" v-permission='"adminDept.add"' aria-hidden="true"
                    title="创建平级" @click.prevent.stop="createNode(data)"></i>
                  <i class="fa fa-toggle-down text-purple pl-10" v-if="data.parent_id == 0"
                    v-permission='"adminDept.add"' aria-hidden="true" title="创建下级"
                    @click.prevent.stop="createChildNode(data)"></i>
                  <i class="fa fa-trash-o text-red pl-10" v-permission='"adminDept.delete"' aria-hidden="true"
                    title="删除" @click.prevent.stop="removeNode(data)"></i>
                </div>
              </div>
            </el-tree>
          </div>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="panel-info">
          <div class="panel-title">设备列表</div>
          <div class="panel-body" v-if="deviceTableShow">
            <z-table :list="list" :tableProps="tableProps" :columns="columns" @editItem="editItem"
              @deleteItem="deleteItem">
              <template v-slot:content="v">
                <span v-if="v.key == 'machine_status'" class="text-label"
                  :style="{background:v.row[v.key]==1?'#67c23a':v.row[v.key]==4?'#e6a23c':'f56c6c'}">
                  {{getMatchingData(v.row[v.key],'machine_status')}}
                </span>
                <span v-else>{{ v.row[v.key] }}</span>
              </template>
            </z-table>
          </div>
        </div>
      </el-col>
    </el-row>
    <zFormDialog :name="name" :data="data" :formProps="formProps" :fields="fields" @submit="submitNode"
      :submitLoading="submitLoading" :visible.sync="editNodeFormVisible"></zFormDialog>
  </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin'
export default {
  name: 'deviceType',
  mixins: [commonMixin],
  components: {},
  props: {},
  data() {
    return {
      name: '设备类型',
      api: this.$api.tpmMachineType,
      baseUrl: this.$api.baseUrl,
      sortLoading: false,
      currentId: 0,
      treeData: [],
      data: {},
      initData: {
        parent_id: 0,
        id: '',
      },
      formProps: {
        dialogWidth: '70%',
        labelWidth: '140px',
      },
      fields: [
        { title: '设备类型名称', key: 'machine_type_name', required: true },
        { title: '设备类型代码', key: 'machine_type_code', required: true },
      ],
      editNodeFormVisible: false,
      indexChangeParents: [],
      filterText: '',
      currentExpands: [],
      defaultExpandedKeys: [],
      // 设备列表
      tableProps: {
        border: true,
        opsColWith: 100,
        fixed: false,
        // highlightCurrentRow: true,
        hideOperations: true,
      },
      columns: [
        { title: '设备类型', key: 'machine_type_name', width: 100 },
        { title: '设备编号', key: 'machine_code', width: 100 },
        { title: '设备名称', key: 'machine_name', width: 100 },
        { title: '设备规格型号', key: 'machine_description', width: 100 },
        { title: '设备出厂编号', key: 'factory_number', width: 140 },
        { title: '制造商', key: 'manufacturer', minWidth: 80 },
        { title: '供应商', key: 'vendor_name', width: 80 },
        { title: '设备状态', key: 'machine_status', width: 100 },
        { title: '签收人', key: 'signed_by', width: 80 },
        { title: '签收日期', key: 'signed_date', width: 100 },
        { title: '管理人', key: 'custodian', width: 80 },
        { title: '登记日期', key: 'register_date', width: 100 },
        { title: '所属工厂', key: 'plant_name', width: 100 },
        { title: '所属线体', key: 'line_name', width: 100 },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改时间', key: 'modify_time', width: 100 },
      ],
      // 设备状态
      deviceStatus: [
        {
          value: 1,
          label: '正常',
        },
        {
          value: 4,
          label: '停用',
        },
        {
          value: 5,
          label: '报废',
        },
      ],
      deviceTableShow: false,
    }
  },
  computed: {},
  watch: {
    // 输入框和保存排序可见的控制
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    data: function (val) {},
  },
  created() {
    this.refreshTree()
  },
  mounted() {},
  methods: {
    // 编辑
    editNode(data) {
      this.pageLoading = true
      this.currentId = data.id
      this.$request(this.api + 'getByid?id=' + data.id)
        .then((r) => {
          this.data = r
          this.editNodeFormVisible = true
        })
        .finally(() => {
          this.pageLoading = false
        })
    },
    // 创建平级和,直接创
    createNode(data) {
      if (data) {
        this.data = { ...this.initData }
        this.data.parent_id = data.parent_id
      } else {
        this.data = { ...this.initData }
      }
      this.editNodeFormVisible = true
    },
    // 创建下级
    createChildNode(data) {
      if (data.parent_id != 0) {
        return this.$message('设备树只能创建二层')
      }
      this.data = { ...this.initData }
      this.data.parent_id = data.id
      this.editNodeFormVisible = true
    },
    // 创建确定
    submitNode() {
      let rules = /^[A-Z0-9^%*&',;=?$x22]+$/
      let val = this.data.machine_type_code
      if (!rules.test(val)) {
        return this.$message.error('设备类型代码必须是大写的字母,数字和特殊字符')
      }
      this.submitLoading = true
      this.$request(this.api + 'add', this.data, 'post')
        .then((r) => {
          this.submitLoading = false
          this.$message.success('操作成功')
          this.editNodeFormVisible = false
          this.refreshTree()
        })
        .catch(() => {
          this.submitLoading = false
        })
    },
    // 删除树
    removeNode(data) {
      let that = this
      this.$confirm('确定要删除这条记录?').then(() => {
        this.pageLoading = true
        this.$request(this.api + 'Delete?id=' + data.id, {}, 'post')
          .then((r) => {
            this.pageLoading = false
            this.$message.success('操作成功')
            this.refreshTree()
          })
          .catch(() => {
            this.pageLoading = false
          })
      })
    },
    // 判断是否可以放置
    allowDrop(draggingNode, dropNode, type) {
      if (type == 'inner') {
        if (dropNode.data.parent_id == 0) {
          return 'next'
        } else {
          return false
        }
      } else {
        return type
      }
    },

    // 拖拽完成时,对数据进行处理
    afterDrop(i, j, type) {
      if (type == 'inner') {
        i.data.parent_id = j.data.id
      } else {
        i.data.parent_id = j.data.parent_id
      }
      this.indexChangeParents.push(i.data.parent_id)
    },
    // 返回节点是否可以显示
    filterMethod(value, data) {
      if (!value) return true
      return data.machine_type_code.includes(value) || data.machine_type_name.includes(value)
    },
    // 获取树形数据
    refreshTree() {
      this.pageLoading = true
      this.$request(this.api + 'GetTreeList')
        .then((r) => {
          this.treeData = r
          this.defaultExpandedKeys = [...this.currentExpands]
          this.pageLoading = false
        })
        .catch((e) => {
          this.pageLoading = false
        })
    },
    // 节点展开的时候触发
    nodeExpand(data) {
      this.currentExpands.push(data.id)
    },
    // 节点关闭的时候触发
    nodeCollapse(data) {
      let i = this.currentExpands.findIndex((x) => x == data.id)
      if (i != -1) this.currentExpands.splice(i, 1)
    },
    // ***************** 新增位置 *********************
    //节点点击
    nodeClick(data) {
      let Data = {
        machine_type_id: data.id,
        page: 1,
        size: 100,
      }
      this.$request(this.baseUrl + 'Tpm/Machine/GetList', Data, 'post').then((r) => {
        const { list } = r
        this.list = list
        this.deviceTableShow = true
      })
    },
    // 获取匹配数据
    getMatchingData(val, code) {
      if (code == 'machine_status') {
        let tmp = this.deviceStatus.find((i) => i.value == val)
        return tmp ? tmp.label : ''
      }
    },
    formateNodeClick(arr, data, list) {
      if (data.parent_id != 0) {
        let index = list.findIndex((el) => el.id == data.parent_id)
        arr.push(list[index].id)
        this.formateNodeClick(arr, list[index], list)
      }
    },
    changeQueryString(arr) {
      this.$nextTick(() => {
        this.$refs.user.query.deptid = arr
        this.$refs.user.research()
      })
    },
  },
}
</script>

<style lang='scss' scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 12px;
  justify-content: space-between;
  padding-right: 8px;
  overflow: hidden;
}
.disabled {
  cursor: not-allowed;
}
::v-deep .el-dropdown {
  font-size: inherit !important;
}
</style>